package com.gitee.maskit.web;

import com.gitee.maskit.utils.Response;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Date;
import java.util.TimeZone;
import java.util.function.Supplier;

public class MaskitResponseAdvice implements ResponseBodyAdvice<Response> {
    private static final Supplier<Date> GMT_NOW = () ->
        new Date(new Date().getTime() - TimeZone.getDefault().getRawOffset());
    private final ReloadableResourceBundleMessageSource source;

    public MaskitResponseAdvice(ReloadableResourceBundleMessageSource source) {
        this.source = source;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return null != returnType && Response.class.isAssignableFrom(
            returnType.getMethod().getReturnType());
    }

    @Override
    public Response beforeBodyWrite(Response body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (null != body) {
            body.setTimestamp(GMT_NOW.get());
            if (null != source && null != body.getError()) {
                body.setMessage(source.getMessage(body.getError(),
                    body.args(), body.getError(), WebHolder.LOCALE.get()));
            }
        }
        return body;
    }
}
